(function ()
{
    $.fn.getAC = function ()
    {
        return $(this).thisOrParent(".jqui-autocomplete:first");
    };

    $.fn.updateAC = function ()
    {
        var ac = $(this).getAC();
        if (ac)
        {
        }
    };

    $.fn.setACValue = function (id, value)
    {
        var ac = $(this).getAC();
        ac.find(".value-input:first").val(id).change()
        ac.find(".search-input:first").val(value);
    };

    $.fn.getACVal = function ()
    {
        return $(this).getAC().find(".value-input:first").val();
    };


    window.createSearchAutoComplete = function ($el)
    {
        var input = $("[data-eid=" + $el.attr('data-source') + "]:first");
        var url = input.attr("data-source-url");
        var termName = input.attr("data-term-name");
        var lookup = input.attr("data-lookup-name");
        var source = null;
        var lastXhr = null;

        if (lookup && lookup.length)
        {
            source = "/AutoComplete/LookupTerm?lookupview=" + lookup;
        }

        input.blur(function ()
        {
            if (input.val() == "" && $el.val() !== "")
                $el.val("").change();
        });

        input.autocomplete({
            minLength: 1,
            source: function (request, response)
            {
                input.addClass("searching").removeClass("not-found");
                lastXhr = $.getJSON(source, request, function (data, status, xhr)
                {
                    if (xhr === lastXhr)
                    {
                        input.removeClass("searching");
                        response(data);
                        if (!data || !data.length)
                            input.addClass("not-found");
                    }
                });
            },
            delay: 300,
            autoFocus: true,
            select: function (event, ui)
            {
                var selected = ui.item;
                if (!selected)
                {
                    if ($el.val() !== "")
                        $el.val("").change();
                }
                else
                {
                    $el.val(selected.value).change();
                    $el.attr("curr-text", selected.text);
                }
                input.val(selected.text);
                event.preventDefault();
            },
            close: function (event, ui)
            {
                if (input.val() == "")
                {
                    if ($el.val() !== "")
                        $el.val("").change();
                }
                else
                {
                    input.val($el.attr("curr-text"));
                }
            }
        });
    };
})();